package cc.rengu.igas.opms.core.service.trans.gateway;

import cc.rengu.igas.channel.cpcn.facade.response.CpcnMchntOrderPayQueryResponse;
import cc.rengu.igas.channel.cpcn.facade.result.Result;
import cc.rengu.igas.opms.common.constant.OpmsParamConstant;
import cc.rengu.igas.opms.common.enums.RespCodeEnum;
import cc.rengu.igas.opms.core.service.base.ManageService;
import cc.rengu.igas.opms.facade.request.CpcnResultQueryRequest;
import cc.rengu.igas.opms.facade.response.CpcnOrderRefundResponse;
import cc.rengu.igas.opms.facade.response.CpcnResultQueryResponse;
import cc.rengu.igas.share.common.constant.ShareParamConstant;
import cc.rengu.igas.share.common.constant.TransCacheConstant;
import cc.rengu.igas.share.core.service.channel.cpcn.CpcnMchntOrderPayQueryService;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.dao.MchntOrderInfoMapper;
import cc.rengu.oltp.service.common.dao.UserOrderInfoMapper;
import cc.rengu.oltp.service.common.dao.impl.MchntOrderInfoMapperImpl;
import cc.rengu.oltp.service.common.dao.impl.UserOrderInfoMapperImpl;
import cc.rengu.oltp.service.common.entity.ChannelCallCfg;
import cc.rengu.oltp.service.common.entity.MchntOrderInfo;
import cc.rengu.oltp.service.common.entity.UserOrderInfo;
import cc.rengu.oltp.service.common.enums.CheckResultEnum;
import cc.rengu.oltp.service.common.enums.TransStatusEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.service.model.OrderInfo;
import cc.rengu.oltp.service.realize.TransCustomImpl;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.GlobalTransUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;

import java.util.List;
import java.util.Optional;

/**
 * 中金企业网关支付结果查询-未使用,废弃
 * T00PM064
 * 收银台->支付通道->中金网关
 *
 * @author fuyp
 * @date 2020/7/21.
 */
public class CpcnResultQueryService extends ManageService implements TransCustomImpl {
    @Override
    protected Object bizBeforeCust() throws Exception {
        CpcnResultQueryRequest cpcnResultQueryRequest = new CpcnResultQueryRequest();
        ConvertUtil.convertOutput(cpcnResultQueryRequest);
        return cpcnResultQueryRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {

        //获取请求数据
        CpcnResultQueryRequest cpcnResultQueryRequest = (CpcnResultQueryRequest) request;
        String instId = cpcnResultQueryRequest.getHeader().getInstId();
        String userOrderId = cpcnResultQueryRequest.getUserOrderId();
        /* 根据订单号查询订单流水号 */
        UserOrderInfoMapper userOrderInfoMapper = new UserOrderInfoMapperImpl();
        UserOrderInfo userOrderInfo = userOrderInfoMapper.selectUserOrderInfoByUserOrderId(instId, userOrderId);
        if (userOrderInfo == null) {
            rglog.info("用户支付订单不存在");
            throw new BizException(RespCodeEnum.ORDER_NOEXIT.getRespCode(), RespCodeEnum.ORDER_NOEXIT.getRespDesc());
        }

        MchntOrderInfoMapper mchntOrderInfoMapper = new MchntOrderInfoMapperImpl();
        List<MchntOrderInfo> mchntOrderInfoList = mchntOrderInfoMapper.selectMchntOrderInfoBySysSeqNum(instId, userOrderInfo.getSysSeqNum());

        CpcnMchntOrderPayQueryService service = new CpcnMchntOrderPayQueryService();
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setMchntOrderInfoList(mchntOrderInfoList);
        orderInfo.setUserOrderInfo(userOrderInfo);
        service.callService(txnInfo, orderInfo, ShareParamConstant.CALL_CFG_DEFAULT_BIZ_SCENE, request);

        //组装响应
        CpcnResultQueryResponse cpcnResultQueryResponse = (CpcnResultQueryResponse) GlobalTransUtil.getCacheValue(TransCacheConstant.BIZ_RESPONSE);
        if (null == cpcnResultQueryResponse) {
            cpcnResultQueryResponse = new CpcnResultQueryResponse();
        }
        cpcnResultQueryResponse.setHeader(cpcnResultQueryRequest.getHeader());
        cpcnResultQueryResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        cpcnResultQueryResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());

        BizResponse<CpcnResultQueryResponse> bizResponse = new BizResponse<>();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(cpcnResultQueryResponse);
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        CpcnResultQueryResponse cpcnResultQueryResponse = (CpcnResultQueryResponse) bizResponse.getResult();
        ConvertUtil.convertInput(cpcnResultQueryResponse);
    }

    @Override
    public ChannelCallCfg channelCallSceneDiscern(Object request, List<ChannelCallCfg> channelCallCfgList) throws Exception {
        Optional<ChannelCallCfg> channelCallCfgOpt = channelCallCfgList.stream().filter(item ->
                item.getBizScene().equals(ShareParamConstant.CALL_CFG_DEFAULT_BIZ_SCENE)).findFirst();
        return channelCallCfgOpt.orElse(null);
    }

    @Override
    public CheckResultEnum channelCallPreCheck(Object request, ChannelCallCfg channelCallCfg, OrderInfo orderInfo) throws Exception {
        return CheckResultEnum.PASSED;
    }

    @Override
    public TransStatusEnum channelCallResultProc(Object request, ChannelCallCfg channelCallCfg, TransStatusEnum transStatusEnum, Object channelResponse, OrderInfo needUpdateOrderInfo) throws Exception {
        if (TransStatusEnum.TRANS_SUCC.equals(transStatusEnum) && null != channelResponse) {
            Result<CpcnMchntOrderPayQueryResponse> callResult = (Result<CpcnMchntOrderPayQueryResponse>) channelResponse;
            CpcnMchntOrderPayQueryResponse cpcnMchntOrderPayQuery = callResult.getResult();
            //校验调用状态
            if (null == cpcnMchntOrderPayQuery) {
                rglog.error("调用中金企业网关支付结果查询服务异常！");
                throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
            }
            if (OpmsParamConstant.DUBBO_OVERTIME.equals(cpcnMchntOrderPayQuery.getRespCode())) {
                rglog.info("调用中金企业网关支付结果查询DUBBO接口-超时，respCode:<{}>,respDesc:<{}>", cpcnMchntOrderPayQuery.getRespCode(), cpcnMchntOrderPayQuery.getRespDesc());
                throw new BizException(RespCodeEnum.BIZ_TIMEOUT_ERROR.getRespCode(), RespCodeEnum.BIZ_TIMEOUT_ERROR.getRespDesc());
            } else if (!OpmsParamConstant.DUBBO_SUCCESS.equals(cpcnMchntOrderPayQuery.getRespCode())) {
                rglog.info("调用中金企业网关支付结果查询DUBBO接口-失败，respCode:<{}>,respDesc:<{}>", cpcnMchntOrderPayQuery.getRespCode(), cpcnMchntOrderPayQuery.getRespDesc());
                throw new BizException(cpcnMchntOrderPayQuery.getRespCode(), cpcnMchntOrderPayQuery.getRespDesc());
            } else {
                rglog.info("调用中金企业网关支付结果查询DUBBO接口-成功，respCode:<{}>,respDesc:<{}>", cpcnMchntOrderPayQuery.getRespCode(), cpcnMchntOrderPayQuery.getRespDesc());
            }
            //中金支付返回商户订单付款账户信息
            CpcnResultQueryResponse cpcnResultQueryResponse = new CpcnResultQueryResponse();
            cpcnResultQueryResponse.setPaymentNo(cpcnMchntOrderPayQuery.getPaymentNo());                      //支付交易流水号
            cpcnResultQueryResponse.setInstitutionID(cpcnMchntOrderPayQuery.getInstitutionId());              //机构编号
            cpcnResultQueryResponse.setOrderStatus(cpcnMchntOrderPayQuery.getStatus());                       //状态
            cpcnResultQueryResponse.setOrderAmt(cpcnMchntOrderPayQuery.getAmount());                          //支付金额
            cpcnResultQueryResponse.setSplitType(cpcnMchntOrderPayQuery.getSplitType());                      //分账模式
            cpcnResultQueryResponse.setSplitResult(cpcnMchntOrderPayQuery.getSplitResult());                  //分账结果
            cpcnResultQueryResponse.setBankNotificationTime(cpcnMchntOrderPayQuery.getBankNotificationTime());//支付平台收到银行通知时间
            cpcnResultQueryResponse.setBankID(cpcnMchntOrderPayQuery.getBankId());                            //付款银行标识
            cpcnResultQueryResponse.setPayerAccountName(cpcnMchntOrderPayQuery.getPayerAccountName());        //付款方账户名称
            cpcnResultQueryResponse.setPayerAccountNumber(cpcnMchntOrderPayQuery.getPayerAccountNumber());    //付款方账号
            cpcnResultQueryResponse.setBankTraceNo(cpcnMchntOrderPayQuery.getBankTraceNo());                  //支付回单流水号
            cpcnResultQueryResponse.setRefundAmount(cpcnMchntOrderPayQuery.getRefundAmount());                //可退款金额
            GlobalTransUtil.setCacheValue(TransCacheConstant.BIZ_RESPONSE, cpcnResultQueryResponse);
        }
        return transStatusEnum;
    }
}
